package cn.lbd.kill.server.controller;

import cn.lbd.kill.api.response.BaseResponse;
import cn.lbd.kill.model.entity.User;
import cn.lbd.kill.model.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private Environment environment;
    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 跳转登录页
     *
     * @return
     */
    @RequestMapping(value = {"/to/login", "/unauth"}, method = RequestMethod.GET)
    public String toLogin() {
        return "login";
    }

    /**
     * 登录认证
     *
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String userName, @RequestParam String password, Model model) {
        String errorMsg = "";
        try {
            //未认证才进行认证
            if (!SecurityUtils.getSubject().isAuthenticated()) {
                String newPwd = new Md5Hash(password, environment.getProperty("shiro.encrypt.password.salt")).toString();
                UsernamePasswordToken token = new UsernamePasswordToken(userName, newPwd);
                //会到Realm组件中去处理认证逻辑
                SecurityUtils.getSubject().login(token);
            }
        } catch (UnknownAccountException e) {
            errorMsg = e.getMessage();
            model.addAttribute("errorMsg", errorMsg);
        } catch (DisabledAccountException e) {
            errorMsg = e.getMessage();
            model.addAttribute("errorMsg", errorMsg);
        } catch (IncorrectCredentialsException e) {
            errorMsg = e.getMessage();
            model.addAttribute("errorMsg", errorMsg);
        } catch (Exception e) {
            errorMsg = "用户登录异常，请联系管理员!";
            e.printStackTrace();
        }
        //没有错误信息说明认证成功，就跳转登录页
        if (StringUtils.isEmpty(errorMsg)) {
            return "redirect:/index";
        } else {
            //登陆失败就回显错误信息和用户名跳回登录页
            model.addAttribute("errorMsg", errorMsg);
            model.addAttribute("userName",userName);
            return "login";
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    @ResponseBody
    public BaseResponse logout() {
        try {
            SecurityUtils.getSubject().logout();
            return new BaseResponse(0, "注销成功");
        } catch (Exception e) {
            return new BaseResponse(1, "注销不成功，请重试");
        }
    }

    /**
     * 跳转注册页
     */
    @RequestMapping("/to/register")
    public String toRegister() {
        return "register";
    }

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    public String register(User user) {
        try {
            user.setPassword(new Md5Hash(user.getPassword(),environment.getProperty("shiro.encrypt.password.salt")).toString());
            logger.info("开始创建用户，用户信息：{}",user);
            userMapper.register(user);
        } catch (Exception e) {
            logger.error("无法创建用户，错误信息：{}",e.getMessage());
        }
        return "/login";
    }
}
